package com.geek.auth.util;

import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Map;

public class SignUtils {
    private static final String SIGN = "token";
    private static final String KEY = "appSecret";

    /**
     *
     * @param data  请求参数
     * @param key    appId秘钥
     * @param charset
     * @return
     */
    public static String sign(Map<String, String> data, String key, String charset) {
        String plain = normalizeMessage(data, key);
        String digest = DigestUtils.md2Hex(StringUtils.getBytesUnchecked(plain, charset));
        return digest.toUpperCase();
    }


    /**
     *
     * @param data  签名文本  请求参数需要按照ascii顺序从小到大排列好
     * @param key  appSecret  外部传入
     * @param charset
     * @return
     */
    public static String sign(String data, String key, String charset) {
        String plain = normalizeMessage(data, key);
        String digest = DigestUtils.md2Hex(StringUtils.getBytesUnchecked(plain, charset));
        return digest.toUpperCase();
    }

    /**
     * 参数规范化（同时加上key值）
     *
     * @param data
     * @param key
     * @return
     */
    private static String normalizeMessage(Map<String, String> data, String key) {
        StringBuilder sb = new StringBuilder();
        data.keySet().stream()
                .filter(name -> !SIGN.equals(name))
                .sorted()
                .forEach(name -> sb.append(name).append("=").append(data.get(name)).append("&"));
        return sb.append(KEY).append("=").append(key).toString();
    }

    private static String normalizeMessage(String data, String key) {
        return data + "&" + KEY + "=" + key;
    }

}
